using demo.Tool;
using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace demo
{
    public partial class Login : Form
    {
        private static Login _instance;
        private static readonly object _lockObject = new object();
        
        // 标志位，防止循环关闭
        private bool isDisposing = false;
        
        public static Login Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lockObject)
                    {
                        if (_instance == null)
                        {
                            operateLog.WriteLog("创建Login单例实例开始");
                            try
                            {
                                _instance = new Login();
                                operateLog.WriteLog("创建Login单例实例成功");
                            }
                            catch (Exception ex)
                            {
                                operateLog.WriteLog("创建Login单例实例失败：" + ex.Message);
                                operateLog.WriteLog("错误堆栈：" + ex.StackTrace);
                                throw;
                            }
                        }
                    }
                }
                return _instance;
            }
        }
        
        private string _user_id;
        private string _password;
        
        // USB存储设备控制器
        private UsbStorageController usbController;
        
        // 壁纸幻灯片管理器
        private WallpaperSlideshow wallpaperSlideshow;
        
        // 主窗体引用（可能是Form1或FormTest）
        private Form mainForm;
        
        // 定时器字段
        private System.Windows.Forms.Timer timerPatientQuery;
        private System.Windows.Forms.Timer timerDataRefresh;
        
        // 公共属性，用于访问USB控制器
        public UsbStorageController UsbController
        {
            get { return usbController; }
        }
        
        // 公共属性，用于访问壁纸幻灯片管理器
        public WallpaperSlideshow WallpaperSlideshow
        {
            get { return wallpaperSlideshow; }
        }
        public Login()
        {
            InitializeComponent();
        }
        
        public void InitializeComponents()
        {
            // 初始化USB存储设备控制器
            usbController = new UsbStorageController();
            
            if (!usbController.IsAdministrator())
            {
                // 提示用户需要管理员权限，但不自动重启
                MessageBox.Show("注意：此程序的某些功能需要管理员权限才能正常工作。\n如需使用USB设备控制功能，请以管理员身份运行程序。",
                "权限提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            
            // 注意：DisplayIPAddress将在主窗体创建后调用，确保窗体完全加载后再执行
            
            //更改操作系统壁纸
            InitializeWallpaperSlideshow();
            
            // 初始化定时器
            InitializeTimers();
            
            // 执行初始化任务
            ExecuteInitializationTasks();
        }

       

        private void bt_login_Click(object sender, EventArgs e)
        {
            if (_user_id == string.Empty)
            {
                MessageBox.Show("请输入用户名:");
                return;
            }
            else if (_password == string.Empty)
            {
                MessageBox.Show("请输入密码:");
                return;
            }
            else
                {
                    _user_id = sle_yh.Text;
                    _password = sle_mm.Text;

                    string url = ConfigurationManager.AppSettings["hisUrl"].ToString() + "His/HisLogin?user_id=" + _user_id + "&password=" + _password;
                    string json = HttpGetJson(url, null);
                    //HttpPostJson
                    if (json == "0")
                    {
                        MessageBox.Show("用户名或密码错误,请输入正确的用户名密码再登录!");
                        sle_yh.Focus();
                        sle_yh.SelectAll();
                        sle_mm.Text = string.Empty;
                    }
                    else {
                        if (json.Contains("|"))
                        {
                            string[] s = json.Split('|');
                            UesrModel user = new UesrModel();
                            user.user_id = _user_id;
                            user.user_name = s[1];
                            user.dep_id = s[2];
                            user.dep_name = s[3];

                            // 保存用户登录信息
                            try
                            {
                                UserLoginManager.SaveUserLoginInfo(_user_id, _password);
                                
                                // 立即刷新用户列表（为下次登录准备）
                                LoadValidUserNames();

                                // 登录后科室选择：如已有本地缓存则跳过，否则弹窗选择并保存
                                var deptInfo = UserLoginManager.GetUserDeptInfo(_user_id);
                                bool needSelectDept = string.IsNullOrWhiteSpace(deptInfo.DeptName) || string.IsNullOrWhiteSpace(deptInfo.OrgCode);
                                if (needSelectDept)
                                {
                                    var permResp = PatientDataService.QueryDoctorOutpDeptPermissions(_user_id);
                                    if (permResp != null && permResp.Data != null && permResp.Data.Count > 0)
                                    {
                                        using (var selectForm = new DoctorDeptSelectForm(permResp.Data))
                                        {
                                            var dr = selectForm.ShowDialog(this);
                                            if (dr == DialogResult.OK && selectForm.SelectedItem != null)
                                            {
                                                UserLoginManager.SetUserDeptInfo(_user_id, selectForm.SelectedItem.DeptName, selectForm.SelectedItem.OrgCode);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        // 无权限数据时给出提示，不影响登录流程
                                        MessageBox.Show("未找到相关门诊科室权限信息，后续功能可能受限。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine($"保存用户登录信息失败: {ex.Message}");
                            }

                            // 根据环境配置选择打开的窗体
                            string environment = ConfigurationManager.AppSettings["Environment"] ?? "Production";
                            
                            if (environment.Equals("Development", StringComparison.OrdinalIgnoreCase))
                            {
                                // 开发环境：同时打开 WinChargeNew（新）与 WinCharge（旧）两个窗体
                                var formNew = new WinChargeNew(user);
                                var formOld = new WinCharge(user);
                                mainForm = formNew; // 保持对其中一个窗体的引用以复用现有逻辑

                                // 隐藏登录窗体
                                this.Hide();

                                // 当两个主窗体都关闭时才关闭登录窗体
                                // 这样支持“先打开新窗体，再关闭旧窗体”的切换流程，不会导致程序提前退出
                                formNew.FormClosed += (eventSender, args) =>
                                {
                                    bool anyMainOpen = Application.OpenForms
                                        .Cast<Form>()
                                        .Any(f => f is WinCharge || f is WinChargeNew);
                                    if (!anyMainOpen)
                                    {
                                        this.Close();
                                    }
                                };
                                formOld.FormClosed += (eventSender, args) =>
                                {
                                    bool anyMainOpen = Application.OpenForms
                                        .Cast<Form>()
                                        .Any(f => f is WinCharge || f is WinChargeNew);
                                    if (!anyMainOpen)
                                    {
                                        this.Close();
                                    }
                                };

                                // 显示两个窗体
                                formNew.Show();
                                formOld.Show();

                                // 在显示窗体后，更新IP地址显示到其中一个窗体（另一个窗体在其自身Load中也会更新）
                                formNew.BeginInvoke(new MethodInvoker(() =>
                                {
                                    this.DisplayIPAddress();
                                }));

                                operateLog.WriteLog("开发环境：同时打开 WinChargeNew 与 WinCharge 两个窗体");
                            }
                            else
                            {
                                // 生产环境：仍按原逻辑仅打开 WinCharge 主窗体，保持环境隔离
                                mainForm = new WinCharge(user);

                                this.Hide(); // 隐藏当前登录窗体，而不是关闭
                                // 修正关闭逻辑：仅当没有任何主窗体（WinCharge/WinChargeNew）打开时才关闭登录窗体
                                mainForm.FormClosed += (eventSender, args) =>
                                {
                                    bool anyMainOpen = Application.OpenForms
                                        .Cast<Form>()
                                        .Any(f => f is WinCharge || f is WinChargeNew);
                                    if (!anyMainOpen)
                                    {
                                        this.Close();
                                    }
                                };
                                mainForm.Show(); // 显示主窗体，使用Show而不是ShowDialog

                                // 在显示主窗体后，更新IP地址显示
                                // 使用BeginInvoke确保在窗体完全加载后再执行
                                mainForm.BeginInvoke(new MethodInvoker(() =>
                                {
                                    this.DisplayIPAddress();
                                }));

                                operateLog.WriteLog("生产环境：打开Form1主窗体");
                            }
                        }
                        else {
                            MessageBox.Show("用户名或密码错误,请输入正确的用户名密码再登录!");
                            sle_yh.Focus();
                            sle_yh.SelectAll();
                            sle_mm.Text = string.Empty;
                        }
                       
                        //Tools.UpdateAppConfig("user_id", user_id);
                        //Tools.UpdateAppConfig("user_name", s[1]);
                        //Tools.UpdateAppConfig("user_dept_code", s[2]);
                        //Tools.UpdateAppConfig("user_dept_name", s[3]);
                        //return true;
                    }
                }
        }

        /// <summary>
        /// 获取已安装软件列表并保存为JSON文件
        /// </summary>
        private string GetInstalledSoftware()
        {
            try
            {
                // 获取系统信息
                string hostName = Dns.GetHostName();
                string ipAddress = "";
                IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
                foreach (IPAddress ip in hostEntry.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        ipAddress = ip.ToString();
                        break;
                    }
                }

                // 获取MAC地址
                string macAddress = "";
                foreach (var nic in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
                {
                    if (nic.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up && nic.NetworkInterfaceType != System.Net.NetworkInformation.NetworkInterfaceType.Loopback)
                    {
                        macAddress = nic.GetPhysicalAddress().ToString();
                        // 格式化MAC地址为XX:XX:XX:XX:XX:XX格式
                        if (macAddress.Length == 12)
                        {
                            macAddress = macAddress.Insert(2, ":").Insert(5, ":").Insert(8, ":").Insert(11, ":").Insert(14, ":");
                        }
                        break;
                    }
                }

                // 检查管理员权限
                bool hasAdminRights = usbController != null && usbController.IsAdministrator();

                // 创建软件列表
                List<object> softwareList = new List<object>();
                
                // 从注册表中获取已安装软件信息
                ProcessRegistryKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", softwareList, "Registry-32bit");
                
                // 64位软件的注册表位置
                ProcessRegistryKey(@"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall", softwareList, "Registry-64bit");

                // 创建JSON数据
                var jsonData = new
                {
                    CollectionTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    ComputerName = Environment.MachineName,
                    HasAdminRights = hasAdminRights,
                    IPAddress = ipAddress,
                    MACAddress = macAddress,
                    SoftwareList = softwareList,
                    TotalCount = softwareList.Count,
                    Message = "成功获取软件列表"
                };

                // 转换为JSON字符串
                string jsonOutput = Newtonsoft.Json.JsonConvert.SerializeObject(jsonData, Newtonsoft.Json.Formatting.Indented);
                return jsonOutput;
                //// 确保目录存在
                //string outputDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SoftwareReports");
                //if (!Directory.Exists(outputDir))
                //{
                //    Directory.CreateDirectory(outputDir);
                //}

                //// 写入文件
                //string outputFile = Path.Combine(outputDir, $"InstalledSoftware_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.json");
                //File.WriteAllText(outputFile, jsonOutput);

                //Console.WriteLine($"已成功保存软件列表到文件: {outputFile}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取已安装软件列表时发生错误: {ex.Message}");
                return "error";
            }
        }

        /// <summary>
        /// 处理注册表键，提取软件信息
        /// </summary>
        /// <param name="registryKey">注册表键路径</param>
        /// <param name="softwareList">软件列表</param>
        /// <param name="source">数据源</param>
        private void ProcessRegistryKey(string registryKey, List<object> softwareList, string source)
        {
            using (Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registryKey))
            {
                if (key != null)
                {
                    foreach (string subkeyName in key.GetSubKeyNames())
                    {
                        try
                        {
                            using (RegistryKey subkey = key.OpenSubKey(subkeyName))
                            {
                                if (subkey != null)
                                {
                                    string displayName = subkey.GetValue("DisplayName") as string;
                                    if (!string.IsNullOrEmpty(displayName))
                                    {
                                        string displayVersion = subkey.GetValue("DisplayVersion") as string ?? "";
                                        string publisher = subkey.GetValue("Publisher") as string ?? "";
                                        string installDate = subkey.GetValue("InstallDate") as string ?? "";
                                        string installLocation = subkey.GetValue("InstallLocation") as string ?? "";
                                        
                                        // 格式化安装日期
                                        if (!string.IsNullOrEmpty(installDate) && installDate.Length == 8)
                                        {
                                            installDate = $"{installDate.Substring(0, 4)}-{installDate.Substring(4, 2)}-{installDate.Substring(6, 2)}";
                                        }

                                        var softwareInfo = new
                                        {
                                            Name = displayName,
                                            Version = displayVersion,
                                            Publisher = publisher,
                                            InstallDate = installDate,
                                            InstallLocation = installLocation,
                                            Source = source
                                        };

                                        softwareList.Add(softwareInfo);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"处理注册表项 {subkeyName} 时发生错误: {ex.Message}");
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 禁用USB存储设备
        /// </summary>
        private void DisableUSBStorageDevices()
        {
            try
            {
                if (usbController != null)
                {
                    usbController.DisableUsbStorageDevices();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"禁用USB存储设备时发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 启用USB存储设备
        /// </summary>
        private void EnableUSBStorageDevices()
        {
            try
            {
                if (usbController != null)
                {
                    usbController.EnableUsbStorageDevices();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"启用USB存储设备时发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 加载本地数据
        /// </summary>
        private void LoadLocalData()
        {
            try
            {
                // 如果有主窗体，则更新主窗体的数据
                if (mainForm != null)
                {
                    // 在UI线程更新界面
                    mainForm.Invoke(new MethodInvoker(() =>
                    {
                        // 清空数据网格
                        var dgvLocalDataProperty = mainForm.GetType().GetProperty("dgvLocalData");
                        if (dgvLocalDataProperty != null)
                        {
                            var dgvLocalData = dgvLocalDataProperty.GetValue(mainForm, null) as DataGridView;
                        if (dgvLocalData != null)
                        {
                            dgvLocalData.Rows.Clear();
                            
                            // 从LocalDbHelper获取数据
                            var localData = LocalDbHelper.GetTodayPatientVisitData();
                            
                            if (localData != null && localData.Count > 0)
                            {
                                // 按outP_VISIT_ID降序排序（最大的在上面）
                                var sortedData = localData.OrderByDescending(x => 
                                {
                                    if (x.ContainsKey("outP_VISIT_ID") && long.TryParse(x["outP_VISIT_ID"], out long id))
                                        return id;
                                    return 0;
                                }).ToList();
                                
                                foreach (var item in sortedData)
                                {
                                    int rowIndex = dgvLocalData.Rows.Add();
                                    
                                    // 查找列并设置值
                                    var colViewButton = dgvLocalData.Columns["colViewButton"];
                                    var colPatientName = dgvLocalData.Columns["colPatientName"];
                                    var colOrderNames = dgvLocalData.Columns["colOrderNames"];
                                    var colOutpVisitId = dgvLocalData.Columns["colOutpVisitId"];
                                    var colPatLevel = dgvLocalData.Columns["colPatLevel"];
                                    var colSpecialName = dgvLocalData.Columns["colSpecialName"];
                                    var outp_visit_id = dgvLocalData.Columns["outp_visit_id"];
                                    var colLisCount = dgvLocalData.Columns["colLisCount"];
                                    var colExamCount = dgvLocalData.Columns["colExamCount"];
                                    var colRegistrationFeeStatus = dgvLocalData.Columns["colRegistrationFeeStatus"];
                                    
                                    if (colViewButton != null) dgvLocalData.Rows[rowIndex].Cells[colViewButton.Index].Value = "查阅";
                                    if (colPatientName != null) dgvLocalData.Rows[rowIndex].Cells[colPatientName.Index].Value = item.ContainsKey("patI_NAME") ? item["patI_NAME"] : "";
                                    if (colOrderNames != null) dgvLocalData.Rows[rowIndex].Cells[colOrderNames.Index].Value = item.ContainsKey("ordeR_NAMES") ? item["ordeR_NAMES"] : "";
                                    if (colOutpVisitId != null) dgvLocalData.Rows[rowIndex].Cells[colOutpVisitId.Index].Value = item.ContainsKey("patienT_ID") ? item["patienT_ID"] : "";
                                    if (colPatLevel != null) dgvLocalData.Rows[rowIndex].Cells[colPatLevel.Index].Value = item.ContainsKey("paT_LEVEL") ? item["paT_LEVEL"] : "";
                                    if (colSpecialName != null) dgvLocalData.Rows[rowIndex].Cells[colSpecialName.Index].Value = item.ContainsKey("outP_SPECIAL_NAME") ? item["outP_SPECIAL_NAME"] : "";
                                    if (outp_visit_id != null) dgvLocalData.Rows[rowIndex].Cells[outp_visit_id.Index].Value = item.ContainsKey("outP_VISIT_ID") ? item["outP_VISIT_ID"] : "";

                                    // 设置互认检验按钮
                                    string lisCount = item.ContainsKey("liS_COUNT") ? item["liS_COUNT"] : "0";
                                    if (colLisCount != null) 
                                    {
                                        dgvLocalData.Rows[rowIndex].Cells[colLisCount.Index].Value = lisCount;
                                        if (lisCount != "0")
                                        {
                                            dgvLocalData.Rows[rowIndex].Cells[colLisCount.Index].Style.BackColor = Color.MediumSpringGreen;
                                        }
                                    }
                                    
                                    // 设置互认检查按钮
                                    string examCount = item.ContainsKey("exaM_COUNT") ? item["exaM_COUNT"] : "0";
                                    if (colExamCount != null) 
                                    {
                                        dgvLocalData.Rows[rowIndex].Cells[colExamCount.Index].Value = examCount;
                                        if (examCount != "0")
                                        {
                                            dgvLocalData.Rows[rowIndex].Cells[colExamCount.Index].Style.BackColor = Color.PeachPuff;
                                        }
                                    }
                                    
                                    if (colRegistrationFeeStatus != null) 
                                    {
                                        dgvLocalData.Rows[rowIndex].Cells[colRegistrationFeeStatus.Index].Value = item.ContainsKey("registratioN_FEE_STATUS") ? item["registratioN_FEE_STATUS"] : "";
                                    }
                                    
                                    // 存储完整的数据对象到Tag中，方便后续使用
                                    dgvLocalData.Rows[rowIndex].Tag = item;
                                }
                            }
                        }
                        }
                    }));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载本地数据时发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 加载医生患者记录
        /// </summary>
        private void LoadDoctorPatientRecords()
        {
            try
            {
                // 调用PatientDataService.GetDoctorPatientRecords接口
                var response = PatientDataService.GetDoctorPatientRecords(_user_id);
                
                if (response != null && response.Success && response.Data != null)
                {
                    // 处理返回的数据
                    foreach (var record in response.Data)
                    {
                        // 构造JSON数据
                        string jsonData = JsonConvert.SerializeObject(new
                        {
                            data = new
                            {
                                outP_VISIT_ID = record.OutpVisitId,
                                patienT_ID = record.PatientId,
                                patI_NAME = record.PatientName,
                                outP_SPECIAL_NAME = record.OutpSpecialName,
                                outP_DATE = record.OutpDate,
                                visiT_ID = record.VisitId,
                                admissioN_DOCTOR = record.AdmissionDoctor,
                                doctoR_VS_OUTP_VISIT_ID = record.DoctorVsOutpVisitId,
                                qR_CODE = record.QrCode,
                                registratioN_FEE_STATUS = record.RegistrationFeeStatus,
                                paT_LEVEL = record.PatLevel,
                                liS_COUNT = record.LisCount,
                                exaM_COUNT = record.ExamCount,
                                reaD_FLAG = record.ReadFlag,
                                ordeR_NAMES = record.OrderNames
                            }
                        });
                        
                        // 保存到本地数据库
                        TimerTaskDataProcessor.ProcessPatientData(jsonData);
                    }
                    
                    // 刷新本地数据
                    LoadLocalData();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载医生患者记录时发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 患者数据查询定时器事件处理
        /// </summary>
        private void TimerPatientQuery_Tick(object sender, EventArgs e)
        {
            try
            {
                // 调用PatientDataService.GetDoctorPatientRecords接口
                var response = PatientDataService.GetDoctorPatientRecords(_user_id);
                
                if (response != null && response.Success && response.Data != null)
                {
                    // 处理返回的数据
                    foreach (var record in response.Data)
                    {
                        // 构造JSON数据
                        string jsonData = JsonConvert.SerializeObject(new
                        {
                            data = new
                            {
                                outP_VISIT_ID = record.OutpVisitId,
                                patienT_ID = record.PatientId,
                                patI_NAME = record.PatientName,
                                outP_SPECIAL_NAME = record.OutpSpecialName,
                                outP_DATE = record.OutpDate,
                                visiT_ID = record.VisitId,
                                admissioN_DOCTOR = record.AdmissionDoctor,
                                doctoR_VS_OUTP_VISIT_ID = record.DoctorVsOutpVisitId,
                                qR_CODE = record.QrCode,
                                registratioN_FEE_STATUS = record.RegistrationFeeStatus,
                                paT_LEVEL = record.PatLevel,
                                liS_COUNT = record.LisCount,
                                exaM_COUNT = record.ExamCount,
                                reaD_FLAG = record.ReadFlag,
                                ordeR_NAMES = record.OrderNames
                            }
                        });
                        
                        // 保存到本地数据库
                        TimerTaskDataProcessor.ProcessPatientData(jsonData);
                    }
                    
                    // 刷新本地数据
                    LoadLocalData();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"患者数据查询定时器事件处理时发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 数据刷新定时器事件处理
        /// </summary>
        private void TimerDataRefresh_Tick(object sender, EventArgs e)
        {
            try
            {
                // 在后台线程执行数据刷新任务，避免阻塞UI
                ThreadPool.QueueUserWorkItem(state =>
                {
                    try
                    {
                        // 清空本地数据库
                        bool clearResult = LocalDbHelper.ClearAllData();
                        
                        // 在UI线程更新界面
                        if (mainForm != null)
                        {
                            mainForm.Invoke(new MethodInvoker(() =>
                            {
                                // 刷新数据窗口显示清空后的状态
                                LoadLocalData();
                                
                                // 重新获取医生接诊数据
                                LoadDoctorPatientRecords();
                            }));
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"数据刷新定时器事件处理时发生错误: {ex.Message}");
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"数据刷新定时器事件处理时发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 初始化定时器
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="headerDic"></param>
        /// <param name="Method"></param>
        /// <returns></returns>
        private static string HttpGetJson(string Url, Dictionary<string, string> headerDic = null, string Method = "GET")
        {
            string jsons;
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);    //创建一个请求示例 
                if (headerDic != null && headerDic.Count > 0)
                {
                    foreach (var item in headerDic)
                    {
                        request.Headers[item.Key] = item.Value; //添加头
                    }
                }
                //request.Headers["键"] = "值"; //添加头
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();  //获取响应，即发送请求

                Stream responseStream = response.GetResponseStream();
                StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
                jsons = streamReader.ReadToEnd();
            }
            catch (Exception)
            {
                return "";
            }
            return jsons;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="paramData"></param>
        /// <param name="headerDic"></param>
        /// <param name="Method"></param>
        /// <returns></returns>
        public static string HttpPostJson(string Url, string paramData, Dictionary<string, string> headerDic = null, string Method = "POST")
        {
            string jsons;
            try
            {
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(Url);
                wbRequest.KeepAlive = false;
                wbRequest.Method = Method;
                wbRequest.ContentType = "application/json";
                wbRequest.ContentLength = Encoding.UTF8.GetByteCount(paramData);
                if (headerDic != null && headerDic.Count > 0)
                {
                    foreach (var item in headerDic)
                    {
                        wbRequest.Headers.Add(item.Key, item.Value);
                    }
                }
                using (Stream requestStream = wbRequest.GetRequestStream())
                {
                    using (StreamWriter swrite = new StreamWriter(requestStream))
                    {
                        swrite.Write(paramData);
                    }
                }
                HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
                using (Stream responseStream = wbResponse.GetResponseStream())
                {
                    using (StreamReader sread = new StreamReader(responseStream))
                    {
                        jsons = sread.ReadToEnd();
                    }
                }
            }
            catch (Exception)
            {
                //MessageBox.Show(ex.Message, "服务连接");
                return "";
            }
            return jsons;
        }

        private void sle_yh_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == Convert.ToChar(13))
            {
                sle_mm.Focus();
                //_user_id = this.Text;
            }
        }

        private void sle_mm_KeyPress(object sender, KeyPressEventArgs e)
        {

            if (e.KeyChar == Convert.ToChar(13))
            {
                bt_login.Focus();
                //_password = this.Text;
            }
        }

        private void bt_cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Login_Load(object sender, EventArgs e)
        {
            string msg = "";
            int code = CodeHelper.getEffectiveDate(ref msg);
            if (code >= 0)
            {
                if (code < 10)
                {
                    MessageBox.Show("授权剩余天数" + code + "天，请尽快联系供应商进行授权使用。");
                }
            }
            else if (code == -99)
            {
                MessageBox.Show(msg);
                this.Close();
                return;
            }
            else
            {
                MessageBox.Show("授权已到期，请联系供应商进行授权使用。");
                this.Close();
                return;
            }
            
            // 初始化用户登录功能
            InitializeUserLoginFeatures();
        }
        
        public void DisplayIPAddress()
        {
            try
            {
                // operateLog.WriteLog("开始获取IP地址");
                string hostName = Dns.GetHostName();
                IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
                string ipAddress = "";

                foreach (IPAddress ip in hostEntry.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        ipAddress = ip.ToString();
                        // operateLog.WriteLog("找到IP地址: " + ipAddress);
                        break;
                    }
                }

                // 如果有主窗体实例，则更新主窗体的IP地址显示
                if (mainForm != null)
                {
                    // operateLog.WriteLog("主窗体已创建，尝试更新IP地址显示");
                    if (mainForm.InvokeRequired)
                    {
                        mainForm.Invoke(new MethodInvoker(() =>
                        {
                            UpdateIPLabel(ipAddress);
                        }));
                    }
                    else
                    {
                        UpdateIPLabel(ipAddress);
                    }
                }
                else
                {
                    // operateLog.WriteLog("主窗体尚未创建，无法更新IP地址显示");
                }
            }
            catch (SocketException e)
            {
                operateLog.WriteLog("获取IP地址时发生套接字错误: " + e.Message);
                MessageBox.Show("发生套接字错误: " + e.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception e)
            {
                operateLog.WriteLog("获取IP地址时发生未知错误: " + e.Message);
                MessageBox.Show("发生未知错误:" + e.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        private void UpdateIPLabel(string ipAddress)
        {
            try
            {
                // 获取主窗体的LB_IP控件并设置其Text属性
                // LB_IP是一个字段而不是属性，所以使用GetField
                // 使用NonPublic和Instance标志来访问非公共实例字段
                var lbIpField = mainForm.GetType().GetField("LB_IP", 
                    System.Reflection.BindingFlags.Public | 
                    System.Reflection.BindingFlags.NonPublic |
                    System.Reflection.BindingFlags.Instance);
                    
                if (lbIpField != null)
                {
                    var lbIpControl = lbIpField.GetValue(mainForm) as Label;
                    if (lbIpControl != null)
                    {
                        lbIpControl.Text = "本机IP:" + ipAddress;
                        // operateLog.WriteLog("成功更新IP地址显示: " + ipAddress);
                    }
                    else
                    {
                        // operateLog.WriteLog("无法获取LB_IP控件实例");
                    }
                }
                else
                {
                    // operateLog.WriteLog("无法获取LB_IP控件字段");
                }
            }
            catch (Exception)
            {
                // operateLog.WriteLog("更新IP地址显示时发生错误");
            }
        }

        private void InitializeWallpaperSlideshow()
        {
            try
            {
                // 获取程序目录下的background文件夹路径
                string backgroundDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "background");
                
                // 初始化壁纸幻灯片管理器，设置切换间隔为10分钟（600秒）
                // 注意：第三个参数单位是分钟，10.0表示10分钟切换一次壁纸
                wallpaperSlideshow = new WallpaperSlideshow(this, backgroundDir, 10.0);
                
                // 启动壁纸切换
                var result = wallpaperSlideshow.Start();
                if (!result.Success)
                {
                    // 如果是因为没有图片文件，给出友好提示
                    if (result.ErrorMessage.Contains("未找到图片文件"))
                    {
                        MessageBox.Show("壁纸切换功能已启用，但background文件夹中没有图片文件。\n\n" +
                                      "请在程序目录下的background文件夹中放置JPG、PNG或BMP格式的图片文件，\n" +
                                      "程序将自动每10分钟切换一次桌面壁纸。", 
                                      "壁纸切换提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show(result.ErrorMessage, "壁纸切换错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("初始化壁纸切换时发生错误: {0}", ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 执行初始化任务
        /// </summary>
        private void ExecuteInitializationTasks()
        {
            // 创建获取已安装软件列表的线程
            Thread softwareThread = new Thread(() =>
            {
                try
                {
                    // 获取已安装软件列表并保存为JSON文件
                    string _url = $"http://10.1.200.169:82/SoftwareInfo/SubmitSoftwareInfo";
                    string _softListJson = GetInstalledSoftware();
                    if (_softListJson != "error")
                    {
                        HttpPostJson(_url, _softListJson);
                    }                    
                    //Console.WriteLine("已成功获取并保存已安装软件列表");
                }
                catch (Exception)
                {
                    //Console.WriteLine($"获取已安装软件列表失败: {ex.Message}");
                }
            });
            softwareThread.IsBackground = true;
            softwareThread.Start();

            // 创建USB控制器操作的线程
            Thread usbThread = new Thread(() =>
            {
                try
                {
                    // 禁用USB存储设备
                    DisableUSBStorageDevices();
                    Console.WriteLine("USB存储设备已禁用");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"禁用USB存储设备失败: {ex.Message}");
                }
            });
            usbThread.IsBackground = true;
            usbThread.Start();

            // 清空本地数据库
            try
            {
                LocalDbHelper.ClearAllData();
                Console.WriteLine("本地数据库已清空");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"清空本地数据库失败: {ex.Message}");
            }

            // 刷新数据窗口
            try
            {
                LoadLocalData();
                Console.WriteLine("数据窗口已刷新");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"刷新数据窗口失败: {ex.Message}");
            }

            // 调用GetDoctorPatientRecords接口
            try
            {
                LoadDoctorPatientRecords();
                Console.WriteLine("医生患者记录已加载");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载医生患者记录失败: {ex.Message}");
            }

            // 启动患者数据查询定时器
            timerPatientQuery.Start();
            Console.WriteLine("患者数据查询定时器已启动");

            // 启动数据刷新定时器
            timerDataRefresh.Start();
            Console.WriteLine("数据刷新定时器已启动");
        }

        private void InitializeTimers()
        {
            // 初始化患者数据查询定时器
            timerPatientQuery = new System.Windows.Forms.Timer();
            timerPatientQuery.Interval = 15000; // 15秒
            timerPatientQuery.Tick += TimerPatientQuery_Tick;
            
            // 初始化数据刷新定时器
            timerDataRefresh = new System.Windows.Forms.Timer();
            timerDataRefresh.Interval = 600000; // 10分钟
            timerDataRefresh.Tick += TimerDataRefresh_Tick;
        }

        /// <summary>
        /// 初始化用户登录功能
        /// </summary>
        private void InitializeUserLoginFeatures()
        {
            try
            {
                // 清理过期的用户信息
                UserLoginManager.CleanExpiredUserInfo();
                
                // 加载有效的用户名到下拉列表
                LoadValidUserNames();
                
                // 设置最后登录的用户为默认选中
                string lastLoginUser = UserLoginManager.GetLastLoginUser();
                if (!string.IsNullOrEmpty(lastLoginUser))
                {
                    sle_yh.Text = lastLoginUser;
                    // 如果可以自动填充密码，则填充
                    if (UserLoginManager.CanAutoFillPassword(lastLoginUser))
                    {
                        string password = UserLoginManager.GetUserPassword(lastLoginUser);
                        if (!string.IsNullOrEmpty(password))
                        {
                            sle_mm.Text = password;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"初始化用户登录功能时发生错误: {ex.Message}");
                MessageBox.Show($"初始化用户登录功能时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 加载有效的用户名到下拉列表
        /// </summary>
        private void LoadValidUserNames()
        {
            try
            {
                sle_yh.Items.Clear();
                var validUserNames = UserLoginManager.GetValidUserNames();
                foreach (string userName in validUserNames)
                {
                    sle_yh.Items.Add(userName);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载用户名列表时发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 用户名选择改变事件处理
        /// </summary>
        private void sle_yh_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                string selectedUser = sle_yh.Text;
                if (!string.IsNullOrEmpty(selectedUser))
                {
                    // 检查是否可以自动填充密码
                    if (UserLoginManager.CanAutoFillPassword(selectedUser))
                    {
                        string password = UserLoginManager.GetUserPassword(selectedUser);
                        if (!string.IsNullOrEmpty(password))
                        {
                            sle_mm.Text = password;
                        }
                        else
                        {
                            sle_mm.Text = string.Empty;
                        }
                    }
                    else
                    {
                        sle_mm.Text = string.Empty;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理用户名选择改变事件时发生错误: {ex.Message}");
                sle_mm.Text = string.Empty;
            }
        }

        /// <summary>
        /// 用户名文本改变事件处理
        /// </summary>
        private void sle_yh_TextChanged(object sender, EventArgs e)
        {
            try
            {
                string currentUser = sle_yh.Text;
                if (!string.IsNullOrEmpty(currentUser))
                {
                    // 检查是否可以自动填充密码
                    if (UserLoginManager.CanAutoFillPassword(currentUser))
                    {
                        string password = UserLoginManager.GetUserPassword(currentUser);
                        if (!string.IsNullOrEmpty(password))
                        {
                            sle_mm.Text = password;
                        }
                        else
                        {
                            sle_mm.Text = string.Empty;
                        }
                    }
                    else
                    {
                        // 如果不是最后登录的用户或密码已过期，清空密码框
                        sle_mm.Text = string.Empty;
                    }
                }
                else
                {
                    sle_mm.Text = string.Empty;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理用户名文本改变事件时发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 创建测试用户数据（仅用于测试）
        /// </summary>
        private void CreateTestUserData()
        {
            try
            {
                // 保存一些测试用户数据
                UserLoginManager.SaveUserLoginInfo("admin", "123456");
                UserLoginManager.SaveUserLoginInfo("test", "test123");
                UserLoginManager.SaveUserLoginInfo("user1", "password1");
                
                Console.WriteLine("已创建测试用户数据");
                
                // 重新加载用户列表
                LoadValidUserNames();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"创建测试用户数据时发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 重写Dispose方法，确保所有资源都被正确释放
        /// </summary>
        /// <param name="disposing">是否释放托管资源</param>
        protected override void Dispose(bool disposing)
        {
            try
            {
                // 防止循环调用
                if (isDisposing)
                {
                    base.Dispose(disposing);
                    return;
                }
                
                isDisposing = true;
                operateLog.WriteLog("开始释放Login窗体资源");
                
                if (disposing)
                {
                    // 停止并释放定时器
                    if (timerPatientQuery != null)
                    {
                        operateLog.WriteLog("停止患者查询定时器");
                        timerPatientQuery.Stop();
                        timerPatientQuery.Dispose();
                        timerPatientQuery = null;
                    }
                    
                    if (timerDataRefresh != null)
                    {
                        operateLog.WriteLog("停止数据刷新定时器");
                        timerDataRefresh.Stop();
                        timerDataRefresh.Dispose();
                        timerDataRefresh = null;
                    }
                    
                    // 释放USB控制器
                    if (usbController != null)
                    {
                        operateLog.WriteLog("释放USB控制器资源");
                        try
                        {
                            // UsbStorageController没有Dispose方法，设置为null即可
                        }
                        catch (Exception ex)
                        {
                            operateLog.WriteLog("释放USB控制器时发生错误：" + ex.Message);
                        }
                        usbController = null;
                    }
                    
                    // 停止壁纸幻灯片
                    if (wallpaperSlideshow != null)
                    {
                        operateLog.WriteLog("停止壁纸幻灯片");
                        try
                        {
                            wallpaperSlideshow.Stop();
                            wallpaperSlideshow.Dispose();
                        }
                        catch (Exception ex)
                        {
                            operateLog.WriteLog("停止壁纸幻灯片时发生错误：" + ex.Message);
                        }
                        wallpaperSlideshow = null;
                    }
                    
                    // 关闭主窗体
                    if (mainForm != null && !mainForm.IsDisposed)
                    {
                        operateLog.WriteLog("关闭主窗体");
                        try
                        {
                            // 先移除事件处理程序，避免循环调用
                            mainForm.FormClosed -= (eventSender, args) => this.Close();
                            
                            // 检查窗体是否仍然有效
                            if (!mainForm.IsDisposed && mainForm.IsHandleCreated)
                            {
                                mainForm.Close();
                            }
                            
                            if (!mainForm.IsDisposed)
                            {
                                mainForm.Dispose();
                            }
                        }
                        catch (Exception ex)
                        {
                            operateLog.WriteLog("关闭主窗体时发生错误：" + ex.Message);
                        }
                        mainForm = null;
                    }
                    
                    // 停止定时任务数据处理器
                    try
                    {
                        operateLog.WriteLog("停止定时任务数据处理器");
                        TimerTaskDataProcessor.Stop();
                    }
                    catch (Exception ex)
                    {
                        operateLog.WriteLog("停止定时任务数据处理器时发生错误：" + ex.Message);
                    }
                    
                    // 释放组件
                    if (components != null)
                    {
                        operateLog.WriteLog("释放窗体组件");
                        components.Dispose();
                    }
                }
                
                operateLog.WriteLog("Login窗体资源释放完成");
            }
            catch (Exception ex)
            {
                // 即使在释放资源时出错，也要确保基类的Dispose被调用
                operateLog.WriteLog("释放Login窗体资源时发生错误：" + ex.Message);
            }
            finally
            {
                // 确保基类的Dispose方法被调用
                base.Dispose(disposing);
            }
        }
        
        /// <summary>
        /// 窗体关闭事件处理
        /// </summary>
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            try
            {
                operateLog.WriteLog("Login窗体正在关闭");
                
                // 在窗体关闭前进行清理工作
                if (timerPatientQuery != null && timerPatientQuery.Enabled)
                {
                    timerPatientQuery.Stop();
                }
                
                if (timerDataRefresh != null && timerDataRefresh.Enabled)
                {
                    timerDataRefresh.Stop();
                }
                
                operateLog.WriteLog("Login窗体关闭前清理完成");
            }
            catch (Exception ex)
            {
                operateLog.WriteLog("Login窗体关闭前清理时发生错误：" + ex.Message);
            }
            finally
            {
                base.OnFormClosing(e);
            }
        }

    }
}
